import BasePanel from "../../framework/BasePanel";

const { ccclass, property } = cc._decorator;

@ccclass
export default class coreAni extends BasePanel<coreAni> {

    @property(cc.Node)
    startPoint: cc.Node = null;
    @property(cc.Node)
    endPoint: cc.Node = null;
    @property(cc.Prefab)
    cointPrefab: cc.Prefab = null;

    coinPool: cc.NodePool = null;

    onLoad() {
        this.coinPool = new cc.NodePool();

        this.initCoinPool();
    }

    initCoinPool(count: number = 20) {
        for (let i = 0; i < count; i++) {
            let coin = cc.instantiate(this.cointPrefab);
            this.coinPool.put(coin);
        }
    }

    playAnim() {
        let randomCount = Math.random() * 15 + 10;
        let stPos = this.startPoint.getPosition();
        let edPos: cc.Vec3 = this.startPoint.parent.convertToNodeSpaceAR(this.endPoint.parent.convertToWorldSpaceAR(this.endPoint.getPosition(new cc.Vec3())))
        this.playCoinFlyAnim(randomCount, stPos, edPos);
    }

    playCoinFlyAnim(count: number, stPos: cc.Vec3, edPos: cc.Vec3, r: number = 130) {
        // 确保当前节点池有足够的金币
        const poolSize = this.coinPool.size();
        const reCreateCoinCount = poolSize > count ? 0 : count - poolSize;
        this.initCoinPool(reCreateCoinCount);

        // 生成圆，并且对圆上的点进行排序
        let points = this.getCirclePoints(r, stPos, count);
        let coinNodeList = points.map(pos => {
            let coin = this.coinPool.get();
            coin.setPosition(stPos);
            this.node.addChild(coin);
            return {
                node: coin,
                stPos: stPos,
                mdPos: pos,
                edPos: edPos,
                dis: (pos as any).sub(edPos).mag()
            };
        });
        coinNodeList = coinNodeList.sort((a, b) => {
            if (a.dis - b.dis > 0) return 1;
            if (a.dis - b.dis < 0) return -1;
            return 0;
        });

        // 执行金币落袋的动画
        coinNodeList.forEach((item, idx) => {
            cc.tween(item.node).to(0.3, { position: item.mdPos }).delay(idx * 0.01).to(.5, { position: item.edPos }).call(() => {
                this.coinPool.put(item.node);
            }).start();
        });
    }

    getCirclePoints(r: number, pos: cc.Vec3, count: number, randomScope: number = 60): cc.Vec3[] {
        let points = [];
        let radians = (Math.PI / 180) * Math.round(360 / count);
        for (let i = 0; i < count; i++) {
            let x = pos.x + r * Math.sin(radians * i);
            let y = pos.y + r * Math.cos(radians * i);
            points.unshift(cc.v3(x + Math.random() * randomScope, y + Math.random() * randomScope, 0));
        }
        return points;
    }

}
